<!DOCTYPE html>
<html>
<head>
<title>数据架构</title>
<meta name="description" content="A concept map diagram implemented with labeled links and ForceDirectedLayout." />
<meta charset="UTF-8">
<link rel="stylesheet" href="${mvcPath}/dacp-lib/bootstrap/css/bootstrap.min.css" type="text/css" />
<link rel="stylesheet" href="${mvcPath}/dacp-view/aijs/css/ai.css" type="text/css" />
<style type="text/css">
  /* CSS for the traditional context menu */
  body{background-color: #f9f9f9;}
  #contextMenu {
    z-index: 300;
    position: absolute;
    left: 5px;
    border: 1px solid #444;
    background-color: #FFF;
    display: none;
    box-shadow: 0 0 10px rgba( 0, 0, 0, .4 );
    font-size: 12px;
    font-family: sans-serif;
  }
  #contextMenu ul {
    list-style: none;
    top: 0;
    left: 0;
    margin: 0;
    padding: 0;
  }
  #contextMenu li a {
    position: relative;
    min-width: 60px;
    color: #444;
    display: inline-block;
    padding: 6px;
    text-decoration: none;
    cursor: pointer;
  }
  #contextMenu li:hover { background: #F3F3F3; }
  #contextMenu li:hover { color: #EEE; }
  #contextMenu li ul li {
      display: none;
  }
  #contextMenu li ul li a{
    position: relative;
    min-width: 60px;
    padding: 6px;
    text-decoration: none;
    cursor: pointer;
  }
  #contextMenu li:hover ul li {
      display: block;
      margin-left: 0px; margin-top: 0px;
  }
  #_global_dlg_form_model{width:100%;}
</style>
<script type="text/javascript" src="${mvcPath}/dacp-lib/jquery/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="${mvcPath}/dacp-lib/bootstrap/js/bootstrap.min.js"></script>
<script src="${mvcPath}/dacp-lib/cryptojs/aes.js" type="text/javascript"></script>
<script src="${mvcPath}/crypto/crypto-context.js" type="text/javascript"></script>
<script src="${mvcPath}/dacp-view/aijs/js/ai.core.js"></script>
<script src="${mvcPath}/dacp-view/aijs/js/ai.field.js"></script>
<script src="${mvcPath}/dacp-view/aijs/js/ai.jsonstore.js"></script>
<script type="text/javascript" src="${mvcPath}/dacp-lib/gojs/go.js"></script>
<script src="${mvcPath}/dacp-view/aijs/js/ai.treeview.js"> </script>
<script src="${mvcPath}/dacp-view/aijs/js/ai.core.js"></script>
<script src="${mvcPath}/dacp-view/aijs/js/ai.field.js"></script>
<script src="${mvcPath}/dacp-view/aijs/js/ai.jsonstore.js"></script>
<script src="${mvcPath}/dacp-view/aijs/js/ai.grid.js"></script>
<script id="code">
var dbName = paramMap.dbName;
var dbCnName;
var dbstore1 = ai.getStoreData("select DBNAME from metadbcfg");
var dbstore2 = ai.getStoreData("select CATALOG_CODE from data_catalog_def");
Array.prototype.contains = function ( needle ) {
  for (i in this) {
    if (this[i] == needle) return true;
  }
  return false;
}
var dbstores1 = [];
var dbstores2 = [];
for(var i=0;i<dbstore1.length;i++){
	dbstores1.push(dbstore1[i]["DBNAME"]);
}
for(var i=0;i<dbstore2.length;i++){
	dbstores2.push(dbstore2[i]["CATALOG_CODE"]);
}
var chk1 = dbstores1.contains(dbName);
var chk2 = dbstores2.contains(dbName);
console.log(dbstores1);
console.log(dbstores2);
console.log(chk1);
console.log(chk2);

var xmlid;
if(chk1){
	var xmlidstore = ai.getStoreData("select XMLID,CNNAME from metadbcfg where DBNAME='"+dbName+"'");
	if(xmlidstore.length>0){
		xmlid = xmlidstore[0]["XMLID"];
		dbCnName = xmlidstore[0]["CNNAME"];
	}
}
if(chk2){
	var catastore = ai.getStoreData("select CATALOG_NAME from data_catalog_def where CATALOG_CODE='"+dbName+"'");
	dbCnName = catastore[0]["CATALOG_NAME"];
}

var sql="select DBNAME,RULECODE,RULENAME,PARENTCODE,RULETYPE,FUNC_id,FUNC_NAME,RULEDEF,RULELEVEL,REMARK from metadb_struct where DBNAME='"+dbName+"'"; 
var	dbstructstore;
var getTreeNodes = function(){
	dbstructstore =  new AI.JsonStore({
	    sql:sql,
	    key:"DBNAME,RULECODE",
	    pageSize:-1,
	    table:"METADB_STRUCT"  
	});
	var treeNodes = [];
	var data = dbstructstore.root;
	for(var i=0;i<data.length;i++){
		var parentCode = data[i].PARENTCODE||dbName;
		treeNodes.push({key:data[i].RULECODE,name:data[i].RULENAME,text:data[i].RULENAME,parent:parentCode});
	}
	//console.log(treeNodes);
	return treeNodes;
}
function buildTables(sql){
	var tabstore = new AI.JsonStore({
		sql:sql,
		key:"TOPICCODE",
	    pageSize:13,
	    table:"tablefile" 
		
	});
	var config = {
		id:"buildtabs",
		bAutoWidth:true,
		store:tabstore,
		pageSize:13,
		containerId : "buildtables",
		nowrap:false,
		showcheck:false,
		celldbclick:function(){},
		columns:[{header : "表名", dataIndex : "DATANAME", width : "180", sortable: true}, 
				{header : "表中文名", dataIndex : "DATACNNAME", width : "180", sortable: true}, 
				{header : "创建时间", dataIndex : "EFF_DATE", width : "180", sortable: true},
				{header : "创建人", dataIndex : "CREATER", width : "180", sortable: true}
				]
	};
	$("#buildtables").empty();
	var grid = new AI.Grid(config);
}
var names = {}; // hash to keep track of what names have been used
var myDiagram;
function init() {
    var $ = go.GraphObject.make;  // for conciseness in defining templates
    myDiagram =
      $(go.Diagram, "myDiagramDiv1",
        {
    	  initialContentAlignment: go.Spot.Center,  // center the content
          initialAutoScale: go.Diagram.UniformToFill,
          // define the layout for the diagram
          layout: $(go.TreeLayout, { nodeSpacing: 5, layerSpacing: 50 })
        });
    
    // Define a simple node template consisting of text followed by an expand/collapse button
    myDiagram.nodeTemplate =
      $(go.Node, "Horizontal",
    		  { contextMenu: $(go.Adornment) },
        { selectionChanged: nodeSelectionChanged },  // this event handler is defined below
        $(go.Panel, "Auto",
          $(go.Shape, { fill: "#1F4963", stroke: null }),
         // $("Button",{click:loadtab}),
          $(go.TextBlock,
            { font: "bold 13px Helvetica, bold Arial, sans-serif",
              stroke: "white", margin: 3 },
            new go.Binding("text", "text"))
            /*,
            { 
                contextMenu: partContextMenu
              }*/
        ),
        $("TreeExpanderButton")
      );
    myDiagram.addDiagramListener("ObjectSingleClicked",function(e){
    	var part = e.subject.part;
    	var key = part.data.key;
    	var title = part.data.name;
    	var sql;
    	if(chk1){
    		if(key==dbName){
        		sql = "select DATANAME,DATACNNAME,EFF_DATE,CREATER,TOPICCODE FROM tablefile WHERE DBNAME='"+dbName+"'";
        	}else{
        		sql = "select DATANAME,DATACNNAME,EFF_DATE,CREATER,TOPICCODE FROM tablefile WHERE DBNAME='"+dbName+"' and TOPICCODE like '"+key+"%'";
        	}
    	}
    	if(chk2){
    		if(key===dbName){
    			var xidstore = ai.getStoreData("SELECT XMLID from metadb_struct_obj WHERE DBNAME='"+dbName+"'");
    			var xidstr;
    			if(xidstore.length>0){
    				xidstr="'";
    				for(var i=0;i<xidstore.length;i++){
        				xidstr+=xidstore[i]["XMLID"]+"','";
        			}
        			xidstr = xidstr.substring(0,xidstr.length-2);
    			}else{
    				xidstr = "''";
    			}
    			sql = "select DATANAME,DATACNNAME,EFF_DATE,CREATER,TOPICCODE FROM tablefile WHERE XMLID in ("+xidstr+")";
    		}else{
    			var xidstore1 = ai.getStoreData("SELECT XMLID from metadb_struct_obj WHERE DBNAME='"+dbName+"' and RULECODE like '"+key+"%'");
    			var xidstr1;
    			if(xidstore1.length>0){
    				xidstr1="'";
    				for(var i=0;i<xidstore1.length;i++){
        				xidstr1+=xidstore1[i]["XMLID"]+"','";
        			}
        			xidstr1 = xidstr1.substring(0,xidstr1.length-2);
    			}else{
    				xidstr1="''";
    			}
    			sql = "select DATANAME,DATACNNAME,EFF_DATE,CREATER,TOPICCODE FROM tablefile WHERE XMLID in ("+xidstr1+")";
    		}
    	}
    	if(dbName=='STDCAT'){
    		return;
    	}
    	buildTables(sql);
    	document.getElementById("buildtitle").innerHTML=title;
    //	alert(part.data.key);
    });
    // Define a trivial link template with no arrowhead.
    myDiagram.linkTemplate =
      $(go.Link,
        { selectable: false },
        $(go.Shape));  // the link shape
    // create the model for the DOM tree
    myDiagram.model =
      $(go.TreeModel, {
        isReadOnly: true,  // don't allow the user to delete or copy nodes
        // build up the tree in an Array of node data
        nodeDataArray: getTreeNodes()
      });
    myDiagram.contextMenu = $(go.Adornment);
    // Override the ContextMenuTool.showContextMenu and hideContextMenu methods
    // in order to modify the HTML appropriately.
    var cxTool = myDiagram.toolManager.contextMenuTool;
    // This is the actual HTML context menu:
    var cxElement = document.getElementById("contextMenu");
    // We don't want the div acting as a context menu to have a (browser) context menu!
    cxElement.addEventListener("contextmenu", function(e) {
      this.focus();
      e.preventDefault();
      return false;
    }, false);
    cxElement.addEventListener("blur", function(e) {
      cxTool.stopTool();
      // maybe start another context menu
      if (cxTool.canStart()) {
        myDiagram.currentTool = cxTool;
        cxTool.doMouseUp();
      }
    }, false);
    cxElement.tabIndex = "1";
    // This is the override of ContextMenuTool.showContextMenu:
    // This does not not need to call the base method.
    cxTool.showContextMenu = function(contextmenu, obj) {
      var diagram = this.diagram;
      if (diagram === null) return;
      if (obj === null) return;//屏蔽全局右键
      // Hide any other existing context menu
      if (contextmenu !== this.currentContextMenu) {
        this.hideContextMenu();
      }
      // Show only the relevant buttons given the current state.
      var cmd = diagram.commandHandler;
      var objExists = obj !== null;
      jQuery('#contextMenu li').attr('curNodeKey',obj.data.key).show();
      // Now show the whole context menu element
      cxElement.style.display = "block";
      // we don't bother overriding positionContextMenu, we just do it here:
      var mousePt = diagram.lastInput.viewPoint;
      cxElement.style.left = mousePt.x + "px";
      cxElement.style.top = mousePt.y + "px";
      // Remember that there is now a context menu showing
      this.currentContextMenu = contextmenu;
    }
    // This is the corresponding override of ContextMenuTool.hideContextMenu:
    // This does not not need to call the base method.
    cxTool.hideContextMenu = function() {
      if (this.currentContextMenu === null) return;
      cxElement.style.display = "none";
      this.currentContextMenu = null;
    }
}



function addNodeDatas(nodeData){
	var model = myDiagram.model;
	if(!model.containsNodeData(nodeData)){
		myDiagram.model.addNodeData(nodeData);
	}else{
		console.log("节点已经存在！不需要重复添加");
	}
}
function addChildNode(pnode){
	isCreate = true;
   	buildDBFrameFormCfg('n');
   	ai.openFormDialog("新增主题规则",dbFrameItems,callBack,null);
   	if(dbName==pnode){
   		$("#RULECODE").val("");
   	   	$("#PARENTCODE").val("");
   	   	$("#PARENTCODE").attr("readOnly","true");
   	}else{
   		$("#RULECODE").val(pnode+"_");
   	   	$("#PARENTCODE").val(pnode);
   	   	$("#PARENTCODE").attr("readOnly","true");
   	}
   	$("#RULETYPE").val("TOPICCODE");
}
var orc;
var opc;
function editCurNode(curnodekey){
	buildDBFrameFormCfg('n');
	var rec = dbstructstore.getRecordByKey(dbName+","+curnodekey);
	dbstructstore.curRecord = rec;
	orc = rec.get("RULECODE");
	opc = rec.get("PARENTCODE");
	ai.openFormDialog("编辑当前节点",dbFrameItems,callBack1,dbstructstore);
}
var callBack1 = function(){
	var rulecode = $("#RULECODE").val();
   	var parentcode = $("#PARENTCODE").val();
   	var rulename = $("#RULENAME").val();
	var ruletype = $("#RULETYPE").val();
	var ruledef = $("#RULEDEF").val();
	var func_id = "";
	var func_name="";
	var funcStore=new AI.JsonStore({
		sql:"select OBJTYPE,OBJNAME from METAOBJMODEL",
		table:"METAOBJMODEL",
		pageSize:-1
	});
	var str=document.getElementsByName("FUNC_ID");
	for(var i=0;i<str.length;i++){
		if(str[i].checked){
			func_id += str[i].value + ",";
			func_name += getFuncName(funcStore,str[i].value.trim()) + ",";
		}
	}
	func_id = func_id.substring(0,func_id.lastIndexOf(","));
	func_name = func_name.substring(0,func_name.lastIndexOf(","));
	if(rulecode&&rulename&&ruletype){
		if(parentcode!=opc||rulecode!=orc){
	   		var isParent = dbstructstore.getRecordByKey(dbName+","+parentcode);
	   		if(isParent || parentcode==""){
	   			
	   		}else{
	   			alert("父级编号不存在");
	   			return false;
	   		}
	   		var _index = rulecode.lastIndexOf("_");
	   		var codePre = rulecode.substr(0,_index);
	   		var codeEnd = rulecode.substr(_index+1,rulecode.length);
	   		if(codePre != parentcode){
				alert("编号需以父级编号为前缀");
				return false;
			}
			if(!codeEnd){
				alert("编号需以父级编号加+\"_\"+编号值组成");
				return false;
			}
			var chkstore = new AI.JsonStore({
				sql:"select DBNAME,RULECODE,RULENAME,PARENTCODE,RULETYPE,FUNC_id,FUNC_NAME,RULEDEF,RULELEVEL,REMARK from metadb_struct where DBNAME='"+dbName+"' and RULECODE NOT like '"+orc+"%'",
				key:"RULECODE",
			    pageSize:-1,
			    table:"METADB_STRUCT"
			});
			var isexist = chkstore.getRecordByKey(rulecode);
			if(isexist){
				alert("当前规则编号已存在11111");
	   			return false;
			}
			dbstructstore.select();
			console.log(dbstructstore);
			var oldrecord = dbstructstore.getRecordByKey(dbName+","+orc);
			dbstructstore.remove(oldrecord);
			var oldnode = myDiagram.model.findNodeDataForKey(orc);
			console.log(oldnode);
			myDiagram.model.removeNodeData(oldnode);
			var newrecord = dbstructstore.getNewRecord();
			//newrecord.set("XMLID",xmlid);
			newrecord.set("DBNAME",dbName);
			newrecord.set("RULECODE",rulecode);
			newrecord.set("PARENTCODE",parentcode);
			newrecord.set("RULENAME",rulename);
			newrecord.set("RULETYPE",ruletype);
			newrecord.set("FUNC_ID",func_id);
			newrecord.set("FUNC_NAME",func_name);
			newrecord.set("RULEDEF",ruledef);
			dbstructstore.add(newrecord);
			var newnode = {key:rulecode,name:rulename,text:rulename,parent:parentcode};
			myDiagram.model.addNodeData(newnode);
	   		var childstore = ai.getStoreData("select RULECODE,PARENTCODE from metadb_struct where DBNAME='"+dbName+"' and RULECODE like '"+orc+"%'");
	   		for(var i=0;i<childstore.length;i++){
	   			if(childstore[i].RULECODE==orc){
	   				
	   			}else{
	   				var oldrec = dbstructstore.getRecordByKey(dbName+","+childstore[i].RULECODE);
	   				var newrec = dbstructstore.getNewRecord();
	   	   			newrec.set("RULECODE",oldrec.get("RULECODE").replace(orc,rulecode));
	   	   			newrec.set("PARENTCODE",oldrec.get("PARENTCODE").replace(orc,rulecode));
	   	   			newrec.set("DBNAME",dbName);
	   	   			newrec.set("RULENAME",oldrec.get("RULENAME"));
	   	   			newrec.set("RULETYPE",oldrec.get("RULETYPE"));
	   	   			newrec.set("FUNC_ID",oldrec.get("FUNC_ID"));
	   	 			newrec.set("FUNC_NAME",oldrec.get("FUNC_NAME"));
	   	 			newrec.set("RULEDEF",oldrec.get("RULEDEF"));
		   	 		var oldNode = myDiagram.model.findNodeDataForKey(childstore[i].RULECODE);
					myDiagram.model.removeNodeData(oldNode);
					var newNode = {key:newrec.get("RULECODE"),name:newrec.get("RULENAME"),text:newrec.get("RULENAME"),parent:newrec.get("PARENTCODE")};
					myDiagram.model.addNodeData(newNode);
	   	 			dbstructstore.remove(oldrec);
	   	 			dbstructstore.add(newrec);
	   			}
	   		}
	   		if(chk1){
	   			var tablestore = new AI.JsonStore({
		   			sql:"select XMLID,TOPICCODE from tablefile where DBNAME='"+dbName+"' and TOPICCODE like '"+orc+"%'",
		   			key:"XMLID",
		   			pageSize:-1,
		   			table:"TABLEFILE"
		   		});
		   		for(var i=0;i<tablestore.getCount();i++){
		   			var rec = tablestore.getAt(i);
		   			rec.set("TOPICCODE",rec.get("TOPICCODE").replace(orc,rulecode));
		   		}
		   		tablestore.commit();
	   		}
	   		if(chk2){
	   			var tablestore2 = new AI.JsonStore({
	   				sql:"select XMLID,RULECODE from metadb_struct_obj where DBNAME='"+dbName+"' and RULECODE like '"+orc+"%'",
		   			key:"XMLID",
		   			pageSize:-1,
		   			table:"metadb_struct_obj"
	   			});
	   			for(var i=0;i<tablestore2.getCount();i++){
	   				var rec2 = tablestore2.getAt(i);
	   				rec2.set("RULECODE",rec2.get("RULECODE").replace(orc,rulecode));
	   			}
	   			tablestore2.commit();
	   		}
	   		dbstructstore.commit();
	   	}
	   	if(parentcode==opc&&rulecode==orc){
	   		dbstructstore.curRecord.set("FUNC_ID",func_id);
		   	dbstructstore.curRecord.set("FUNC_NAME",func_name);
		   	dbstructstore.commit();
	   	}
	}else{
		alert("请填写带\" * \"的必填项！22222");
		return false;
	}
   	
   	
   	
};
function deleteCurNode(curnodekey,curnode){
	var childstore = ai.getStoreData("select RULECODE from metadb_struct where DBNAME='"+dbName+"' and RULECODE like '"+curnodekey+"%'");
	if(childstore.length>1){
		var result1 = confirm("删除此节点的同时会删除其所有子节点!您确定要删除吗？");
		if(result1){
			for(var i=0;i<childstore.length;i++){
				var rulecode = childstore[i].RULECODE;
				var record = dbstructstore.getRecordByKey(dbName+","+rulecode);
				dbstructstore.remove(record);
				var node = myDiagram.model.findNodeDataForKey(rulecode);
				myDiagram.model.removeNodeData(node);
			}
		}
	}else{
		var rec = dbstructstore.getRecordByKey(dbName+","+curnodekey);
		var result = confirm("是否删除此节点?");
		if(result){
			dbstructstore.remove(rec);
			myDiagram.model.removeNodeData(curnode);
		}
	}
	dbstructstore.commit();
	
}

function deleteChildNode(curnodekey){
	var childstore = ai.getStoreData("select RULECODE from metadb_struct where DBNAME='"+dbName+"' and RULECODE like '"+curnodekey+"%'");
	if(childstore.length>1){
		var result = confirm("您确定要删除所有子节点码？");
		if(result){
			for(var i=0;i<childstore.length;i++){
				var rulecode = childstore[i].RULECODE;
				if(rulecode==curnodekey){
					continue;
				}
				var node = myDiagram.model.findNodeDataForKey(rulecode);
				var record = dbstructstore.getRecordByKey(dbName+","+rulecode);
				dbstructstore.remove(record);
				myDiagram.model.removeNodeData(node);
			}
			dbstructstore.commit();
		}
	}else{
		alert("此节点没有子节点！");
		return;
	}
	
}

// This is the general menu command handler, parameterized by the name of the command.
var curNodeKey;
function cxcommand(liDom) {
  var diagram = myDiagram;
  if (!(diagram.currentTool instanceof go.ContextMenuTool)) return;
  var name = jQuery(liDom).attr('name');
  curNodeKey = jQuery(liDom).attr('curnodekey');
  var focusNode = diagram.model.findNodeDataForKey(curNodeKey);
  console.log(focusNode);
  switch (name) {
    case "addChildNode": addChildNode(curNodeKey); break;
    case "editCurNode": editCurNode(curNodeKey); break;
    case "deleteCurNode": deleteCurNode(curNodeKey,focusNode); break;
    case "deleteChildNode": deleteChildNode(curNodeKey); break;
    case "addChildTable":addChildTable(curNodeKey);break;
  }
  diagram.currentTool.stopTool();
}

function addChildTable(curNodeKey){
	if(curNodeKey==dbName){
		alert("这是根数据库无法添加");
		return;
	}
	var addsql;
	if(chk1){
		addsql = "select XMLID keyfield,DATANAME values1,DATACNNAME values2,REMARK values3 from tablefile WHERE DBNAME='"+dbName+"' and (TOPICCODE not like '"+curNodeKey+"%' or TOPICCODE IS NULL)";
	}
	if(chk2){
		/*
		var idstore = ai.getStoreData("SELECT XMLID from metadb_struct_obj WHERE DBNAME='"+dbName+"' and (RULECODE not like '"+curNodeKey+"%' or RULECODE IS NULL)");
		var idstr;
		if(idstore.length>0){
			idstr="'";
			for(var i=0;i<idstore.length;i++){
				idstr+=idstore[i]["XMLID"]+"','";
			}
			idstr = idstr.substring(0,idstr.length-2);
		}else{
			idstr = "''";
		}
		*/
		addsql = "select XMLID keyfield,DATANAME values1,DATACNNAME values2,REMARK values3 FROM tablefile";
	}
	var selBox = new SelectBox({sql:addsql,callback:afterSelect});
	selBox.show();
}
function afterSelect(records){
	console.log(records);
	if(chk1){
		var sql = "update tablefile set TOPICCODE='"+curNodeKey+"' where XMLID IN ('";
		for(var i=0;i<records.length;i++){
			var xmid = records[i].get("KEYFIELD");
			sql+=xmid+"','";
		}
		sql = sql.substring(0,sql.length-2);
		sql+=")";
		ai.executeSQL(sql);
		var sql1 = "select DATANAME,DATACNNAME,EFF_DATE,CREATER,TOPICCODE FROM tablefile WHERE DBNAME='"+dbName+"' and TOPICCODE like '"+curNodeKey+"%'";
		buildTables(sql1);
	}else{
		var existidstore = ai.getStoreData("select XMLID from metadb_struct_obj where DBNAME='"+dbName+"'");
		var existidarr = [];
		for(var i=0;i<existidstore.length;i++){
			existidarr.push(existidstore[i].XMLID);
		}
		
		for(var i=0;i<records.length;i++){
			if(!existidarr.contains(records[i].get("KEYFIELD"))){
				var newtabdata = ai.getStoreData("select XMLID,DATANAME from tablefile where XMLID='"+records[i].get("KEYFIELD")+"'");
				var newtabsql = "insert into metadb_struct_obj (DBNAME,RULECODE,XMLID,OBJNAME) values ('"+dbName+"','"+curNodeKey+"','"+newtabdata[0].XMLID+"','"+newtabdata[0].DATANAME+"')";
				ai.executeSQL(newtabsql);
			}else{
				var sql2 = "update metadb_struct_obj set RULECODE='"+curNodeKey+"' where DBNAME='"+dbName+"' and XMLID='"+records[i].get("KEYFIELD")+"'";
				ai.executeSQL(sql2);
			}
		}
		var xidstore1 = ai.getStoreData("SELECT XMLID from metadb_struct_obj WHERE DBNAME='"+dbName+"' and RULECODE like '"+curNodeKey+"%'");
		var xidstr1="'";
		for(var i=0;i<xidstore1.length;i++){
			xidstr1+=xidstore1[i]["XMLID"]+"','";
		}
		xidstr1 = xidstr1.substring(0,xidstr1.length-2);
		var sql3 = "select DATANAME,DATACNNAME,EFF_DATE,CREATER,TOPICCODE FROM tablefile WHERE XMLID in ("+xidstr1+")";
		buildTables(sql3);
	}
}
// When a Node is selected, highlight the corresponding HTML element.
function nodeSelectionChanged(node) {
}
/*
function buildDataStruct(caneditable){
	dbstructstore =  new AI.JsonStore({
	    sql:sql,
	    key:"DBNAME,RULECODE",
	    pageSize:-1,
	    table:"METADB_STRUCT"  
	});	
	var config = {
		id : "datastructx",
		width : "800",
		renderTo : "datastruct",
		headerAlign : "left",
		headerHeight : "30",
		dataAlign : "left",
		indentation : "20",
		showcheck: 'true',
		//folderOpenIcon: "images/folderOpen.gif",
		//folderCloseIcon: "images/folderClose.gif",
		//defaultLeafIcon: "images/defaultLeaf.gif",
		hoverRowBackground : "true",
		folderColumnIndex : "0",
		itemClick : itemClickEvent,
		columns : [ 
			{headerText : "中文名称", dataField : "RULENAME", headerAlign : "center", width : "220", width : "100",editable:caneditable},
			{headerText : "名称", dataField : "RULECODE", headerAlign : "center", width : "120" , dataAlign : "center"}, 
			//{headerText : "中文名", dataField : "PARENTCODE", headerAlign : "center", width : "80" }, 
			{headerText : "类型", dataField : "RULETYPE", headerAlign : "center", width : "80", dataAlign : "center", width : "100",editable:caneditable},
			{headerText : "可包含对象", dataField : "FUNC_ID", headerAlign : "center", width : "120", dataAlign : "center", width : "100",editable:caneditable} 
			//,{headerText : "命名约束类型", dataField : "FUNC_NAME", headerAlign : "center", width : "120", dataAlign : "center", width : "100"}, 
			//{headerText : "命名规则", dataField : "RULEDEF", headerAlign : "center", width : "120", dataAlign : "center", width : "100"}, 
			//{headerText : "英文简称", dataField : "RULELEVEL", headerAlign : "center", width : "120", dataAlign : "center", width : "100"}, 
			 
		],
		keyfield : "RULECODE",
		pkeyfield : "PARENTCODE",
		titlefield : "RULENAME",
		iconfield : "",
		//sql : sql,
		store:dbstructstore,
		subtype : 'treegrid'
	};
	function itemClickEvent(id, index, data) {
		console.log(id + ", " + index + ", "+ TreeGrid.json2str(data));
	}

	/*
		通过指定的方法来自定义栏数据
		此渲染方式暂时屏蔽
	 */
	 /*
	function customCheckBox(row, col) {
		return "<input type='checkbox'>";
	}


	function customLook(row, col) {
		return "<a href='' style='color:blue;'>查看</a>";
	}

	//创建一个组件对象
	$("#datastruct").empty();
	var treeGrid = new TreeGrid(config);
	treeGrid.show();
	//将输入框的宽度设置为填充父级
	if(caneditable){
		$('#datastruct td input[type="text"]').width("100%");
	}
	//将类型渲染为下拉框形式
	$("#datastruct tr").each(function(){
		var pid = $(this).attr("pid") + "";
		var pidIndex = pid.indexOf("TRdatastruct");
		var rule_type = $(this).children("td:last-child").prev().text();
		if(pidIndex != -1){
			var obj = $(this).attr("data");
			obj = eval("("+obj+")");
			var selectID = obj.RULECODE + "Select";
			var defaultVal = obj.RULETYPE + "";
			if(caneditable){ 
				if(pid != "TRdatastruct"){
					var ruleTypeSelect = $('<select style="width:100%;" id='+selectID+'></select>');
					//ruleTypeSelect.append('<option value=""></option>');
					ruleTypeSelect.append('<option value="TOPICNAME">主题</option>');
					ruleTypeSelect.append('<option value="LEVELNAME">层次</option>');
					$(this).children("td:last-child").prev().empty();
					ruleTypeSelect.val(defaultVal);
					$(this).children("td:last-child").prev().append(ruleTypeSelect);
				}
			}else{
				switch(rule_type){
					case 'LEVELNAME': 
						$(this).children("td:last-child").prev().text("层次");
						break;
					case 'TOPICNAME': 
						$(this).children("td:last-child").prev().text("主题");
						break;
					default : 
						$(this).children("td:last-child").prev().text("");
						break;
				}
			}
		}
	});
}
*/
var isCreate = true;
function buildDBFrameFormCfg(isAdd){
		dbFrameItems = [
		{type:'text',label:'规则编号',fieldName:'RULECODE',notNull:'N',width:320,isReadOnly:isAdd},
		{type:'text',label:'上级编号',fieldName:'PARENTCODE',width:320,isReadOnly:isAdd},
		{type:'text',label:'名称',fieldName:'RULENAME',notNull:'N',width:320},
		{type:'combox',label:'节点类型',fieldName:'RULETYPE',notNull:'N',storesql:'TOPICCODE,节点|TOPICNAME,主题|LEVELNAME,层次',width:320},
		{type:'checkbox',label:'可包含对象',fieldName:'FUNC_ID',storesql:"select OBJTYPE,OBJNAME from METAOBJMODEL where PARENTCODE is not null and parentcode<>'META-OTHER' and parentcode<>'META' and STATE = 'Y' order by ORDSEQ asc ",width:320},
		//{type:'pick-grid',label:'可包含对象',fieldName:'FUNC_ID',storesql:'select objtype,objname from metaobjmodel where using_stat=\'Y\'',width:320}
		//,{type:'text',label:'命名约束类型',fieldName:'FUNC_NAME',width:320},
		{type:'text',label:'分类规则',fieldName:'RULEDEF',width:320},
		//{type:'text',label:'英文简称',fieldName:'RULELEVEL',width:320}
	];
}
var renderForm = function(){
	var curRecord = dbstructstore.curRecord;
   	isCreate = true;
   	buildDBFrameFormCfg('n');
   	ai.openFormDialog("新增主题规则",dbFrameItems,callBack,null);
	if(curRecord){
   		$("#RULECODE").val(curRecord.get("RULECODE")+"_");
   		$("#PARENTCODE").val(curRecord.get("RULECODE"));
   	}else{
   		$("#RULECODE").val(objcode+"_");
   		$("#PARENTCODE").val("");
   	}
	$("#RULETYPE").val("TOPICCODE");
}
function getFuncName(store,func_id){
		for(var i=0;i<store.getCount();i++){
			if(store.getAt(i).get("OBJTYPE").trim()==func_id){
				return store.getAt(i).get("OBJNAME");
			}else{
				continue;
			}
		}
		return "...";
}

var callBack =function(){
   	var rulecode = $("#RULECODE").val();
   	var parentcode = $("#PARENTCODE").val();
   	var rulename = $("#RULENAME").val();
	var ruletype = $("#RULETYPE").val();
	var ruledef = $("#RULEDEF").val();
	var func_id = "";
	var func_name="";
	var funcStore=new AI.JsonStore({
		sql:"select OBJTYPE,OBJNAME from METAOBJMODEL",
		table:"METAOBJMODEL",
		pageSize:-1
	});
	var str=document.getElementsByName("FUNC_ID");
	for(var i=0;i<str.length;i++){
		if(str[i].checked){
			func_id += str[i].value + ",";
			func_name += getFuncName(funcStore,str[i].value.trim()) + ",";
		}
	}
	func_id = func_id.substring(0,func_id.lastIndexOf(","));
	func_name = func_name.substring(0,func_name.lastIndexOf(","));
	var rec = dbstructstore.getNewRecord();
	rec.set("XMLID",xmlid);
   	rec.set("DBNAME",dbName);
   	rec.set("RULECODE",rulecode);
   	rec.set("PARENTCODE",parentcode);
   	rec.set("RULENAME",rulename);
   	rec.set("RULETYPE",ruletype);
   	rec.set("FUNC_ID",func_id);
   	rec.set("FUNC_NAME",func_name);
   	rec.set("RULEDEF",ruledef);
   	var nodeData = {key:rulecode,name:rulename,text:rulename,parent:parentcode};
   	//先校验上级编号是否是存在
   	if(parentcode){
   		var isParent = dbstructstore.getRecordByKey(dbName+","+rec.get("PARENTCODE"));
   		if(isParent || parentcode==""){
   			
   		}else{
   			alert("父级编号不存在");
   			return false;
   		}
   	}
   	//再校验当前编号是否按照规则
   	if(rulecode && rulename && ruletype){
   		if(isCreate){
   			var oldStructDataStoreSql = "select DBNAME,RULECODE,RULENAME,PARENTCODE,RULETYPE,FUNc_id,FUNC_NAME,RULEDEF,RULELEVEL,REMARK from metadb_struct where DBNAME='"+dbName+"'";
   			var oldStructDataStore = new AI.JsonStore({
   				sql:oldStructDataStoreSql,
                key:"RULECODE",
                pageSize:-1,
                table:"METADB_STRUCT"
   			});
   			var isExist = oldStructDataStore.getRecordByKey(rulecode);
	   		if(isExist){
	   			alert("当前规则编号已存在");
	   			return false;
	   		}
   		}
   		var _index = rulecode.lastIndexOf("_");
   		var codePre = rulecode.substr(0,_index);
   		var codeEnd = rulecode.substr(_index+1,rulecode.length);
   		if(parentcode){
   			if(codePre != parentcode){
   				alert("编号需以父级编号为前缀");
   				return false;
   			}
   			if(!codeEnd){
   				alert("编号需以父级编号加+\"_\"+编号值组成");
   				return false;
   			}
   		}else{
   		/*校验是否以当前数据库名为前缀
   			if(codePre != objcode){
   				alert("编号需以当前数据库编号为前缀");
   				return false;
   			}
   			if(!codeEnd){
   				alert("编号需以当前数据库编号加+\"_\"+编号值组成！");
   				return false;
   			}
   		*/
   		}
   	}else{
   		alert("请填写带\" * \"的必填项！");
		return false;
   	}
   	if(isCreate){
   		dbstructstore.add(rec);
   	}else{
   		dbstructstore.curRecord.set("FUNC_NAME",func_name);
   	}
   	dbstructstore.commit();
   	dbstructstore.select();
   	addNodeDatas(nodeData);
   	//buildDataStruct();
    $("#batchEditDataStruct").html("<i class='glyphicon glyphicon-user'></i>"+"批量编辑");
	f_batch=false;
}

$(document).ready(function() {
	if(dbName=='STDCAT'){
		$("#myDiagramDiv1").css("width","100%");
		$("#buildtable").hide();
		$("#selecdbtopic").hide();
		$("#tableToStruct").hide();
		$("#contextMenu2").attr("id","contextMenu");
		$("#contextMenu1").hide();
		//$("#contextMenu ul").remove($("#addChildTable"));
	}else{
		$("#contextMenu1").attr("id","contextMenu");
		$("#contextMenu2").hide();
	}
	if(!chk1&&!chk2&&dbName!='STDCAT'){
		alert("不存在的库或业务！")
		return;
	}
	if(chk1){
		var sql = "select DATANAME,DATACNNAME,EFF_DATE,CREATER,TOPICCODE FROM tablefile WHERE DBNAME='"+dbName+"'";
		document.getElementById("buildtitle").innerHTML=dbCnName;
		buildTables(sql);
	}
	if(chk2){
		var xidstore = ai.getStoreData("SELECT XMLID from metadb_struct_obj WHERE DBNAME='"+dbName+"'");
		var xidstr;
		if(xidstore.length>0){
			xidstr="'";
			for(var i=0;i<xidstore.length;i++){
				xidstr+=xidstore[i]["XMLID"]+"','";
			}
			xidstr = xidstr.substring(0,xidstr.length-2);
		}else{
			xidstr="''";
		}
		var sql = "select DATANAME,DATACNNAME,EFF_DATE,CREATER,TOPICCODE FROM tablefile WHERE XMLID in ("+xidstr+")";
		document.getElementById("buildtitle").innerHTML=dbCnName;
		buildTables(sql);
	}
	init();
	/*
	$('.switch-view label').click(function(e){
		var type = $(this).find('input').val();
		if(type == 'map'){
			$('#myDiagramDiv').show();
			$('#datastruct').hide();
			init();
		}
		else{
			$('#myDiagramDiv').hide();
			$('#datastruct').show();
			buildDataStruct();
		}
	});
	*/
	$('#selecdbtopic').click(function(){
        ai.loadWidget("dialog");
		art.dialog({
			title: '数据库主题选择:'+dbName,
			width: 860,height:300,
			content: '<div style="height:300px;overflow:auto;" id="selectdbtopic"></div>',
			init: function () {
			},
			ok: function () {
				var selDataArray=seltreeGrid.getAllCheck();
				var rulcodestore = ai.getStoreData("select RULECODE from metadb_struct where DBNAME='"+dbName+"'");
				rulecodearr = [];
				for(var i=0;i<rulcodestore.length;i++){
					rulecodearr.push(rulcodestore[i].RULECODE);
				}
				if(selDataArray.length==0) {alert('你没有选择记录');return false;};
				for(var i=0;i<selDataArray.length;i++){
					if(rulecodearr.contains(selDataArray[i].RULECODE)){
						console.log("节点"+selDataArray[i].RULECODE+"已存在！添加失败！");
						continue;
					}
					var sql = "insert into metadb_struct (DBNAME,RULECODE,RULENAME,PARENTCODE,RULETYPE,FUNC_ID,FUNC_NAME,RULEDEF) values ('"+dbName+"','"+selDataArray[i].RULECODE+"','"+selDataArray[i].RULENAME+"','"+selDataArray[i].PARENTCODE+"','"+selDataArray[i].RULETYPE+"','"+selDataArray[i].FUNC_ID+"','"+selDataArray[i].FUNC_NAME+"','"+selDataArray[i].RULEDEF+"')";
					ai.executeSQL(sql);
					var nodeData = {key:selDataArray[i].RULECODE,name:selDataArray[i].RULENAME,text:selDataArray[i].RULENAME,parent:selDataArray[i].PARENTCODE};
					addNodeDatas(nodeData);
				}
				dbstructstore.select();
				return true;
				},
			cancel:function(){
				}
		});
		selsql="select DBNAME,RULECODE,RULENAME,PARENTCODE,RULETYPE,FUNC_ID,FUNC_NAME,RULEDEF from metadb_struct where DBNAME='STDCAT'";
		var dbStrutStore=  new AI.JsonStore({
	        sql:selsql,
	        key:"DBNAME,RULECODE",
	        pageSize:-1,
	        table:"METADB_STRUCT"  
		});
		var config = {
				id : "selectdbtopic",
				width : "800",
				renderTo : "selectdbtopic",
				headerAlign : "left",
				headerHeight : "30",
				dataAlign : "left",
				indentation : "8",
				hoverRowBackground : "true",
				folderColumnIndex : "0",
				showcheck:true,
				columns : [ 
					{headerText : "主题编号", dataField : "RULECODE", headerAlign : "center", width : "180" }, 
					{headerText : "数据库名", dataField : "DBNAME", headerAlign : "center", width : "120" },
					{headerText : "主题名称", dataField : "RULENAME", headerAlign : "center", width : "120", dataAlign : "center", width : "100"}
				],
				keyfield : "RULECODE",
				pkeyfield : "PARENTCODE",
				titlefield : "RULENAME",
				iconfield : "",
				store:dbStrutStore,
				subtype : 'treegrid'
			};
		var seltreeGrid = new TreeGrid(config);
	    seltreeGrid.show();
	});
	$('#addSingleNode').click(function(){
		renderForm();
	});

	$('#tableToStruct').click(function(){
		var obj = {};
		if(chk1){
			obj.catatype = 'resource'; 
		}else{
			obj.catatype = 'busi'; 
		}
		obj.setcode = dbName;
		// var data = JSON.stringify(obj);
		console.log(obj);

		$.ajax({ 
			type: "POST",
			// contentType: "application/json", 
			url:'${mvcPath}/catalog/autocatalog',
			async: false,
			data: obj,
			success:function(data) {
				var result = data.message;
				if(data.error) {
					result += ";  " + data.error;
				}
				alert(result);
			},
			error:function(data) {
				alert(JSON.stringify(data));
			}
   		});
		if(chk1){
			var sql = "select DATANAME,DATACNNAME,EFF_DATE,CREATER,TOPICCODE FROM tablefile WHERE DBNAME='"+dbName+"'";
			document.getElementById("buildtitle").innerHTML=dbCnName;
			buildTables(sql);
		}
		if(chk2){
			var xidstore = ai.getStoreData("SELECT XMLID from metadb_struct_obj WHERE DBNAME='"+dbName+"'");
			var xidstr;
			if(xidstore.length>0){
				xidstr="'";
				for(var i=0;i<xidstore.length;i++){
					xidstr+=xidstore[i]["XMLID"]+"','";
				}
				xidstr = xidstr.substring(0,xidstr.length-2);
			}else{
				xidstr="''";
			}
			var sql = "select DATANAME,DATACNNAME,EFF_DATE,CREATER,TOPICCODE FROM tablefile WHERE XMLID in ("+xidstr+")";
			document.getElementById("buildtitle").innerHTML=dbCnName;
			buildTables(sql);
		}
	});

});
</script>
</head>
<body style="height:100%;">
	<div style="padding:10px;">
		<div>
			<button id="addSingleNode" class="btn btn-danger  btn-xs " enabled="">  <i class="glyphicon glyphicon-user"></i>新增节点</button>
			<button id="selecdbtopic" class="btn btn-danger  btn-xs " enabled="">  <i class="glyphicon glyphicon-user"></i>选择主题</button>
			<button id="tableToStruct" class="btn btn-danger  btn-xs " enabled="">  <i class="glyphicon glyphicon-user"></i>表自动归档</button>
			<!-- 
			<button id="importDataStruct" class="btn btn-danger  btn-xs " enabled="">  <i class="glyphicon glyphicon-user"></i>导入</button>
			<button id="copyFromOtherDB" class="btn btn-danger  btn-xs " enabled="">  <i class="glyphicon glyphicon-user"></i>从其它库复制</button>
			<button id="saveDataStruct" class="btn btn-danger  btn-xs " enabled="">  <i class="glyphicon glyphicon-user"></i>保存</button>
			<button id="tableToStruct" class="btn btn-danger  btn-xs " enabled="">  <i class="glyphicon glyphicon-user"></i>表自动归档</button>
			<button id="viewDataindex" class="btn btn-danger  btn-xs " enabled="">  <i class="glyphicon glyphicon-user"></i>数据目录</button>
			 -->
		<div class="pull-right">         
        	<div class="btn-group switch-view" data-toggle="buttons">
        		 <!-- <label class="btn btn-default btn-sm active"><input name="repeaterViews" type="radio" value="map"><span class="glyphicon glyphicon-indent-left"></span></label> -->                                                                                                                          
        		 <!-- <label class="btn btn-default btn-sm"><input name="repeaterViews" type="radio" value="list"><span class="glyphicon glyphicon-list"></span></label> -->                                                                                                                       
        	</div>                                                                                                                          
        </div>
		</div>
		<div id="myDiagramDiv" style="background-color: #fff; border: solid 1px #ddd; width:100%; min-height: 580px;margin-top:10px;">
			<div id="myDiagramDiv1" style="float:left; background-color: #fff; border: solid 1px #ddd; width: 55%; min-height: 580px;"></div>
			<div id="buildtable" style="background-color: #fff; float:left; width:45%; height:580px; border: solid 1px #ddd;">
				<div id="buildtitle" style="background-color: #d9edf7; width:100%; height:28px;border: solid 1px #ddd;line-height:28px;padding-left:14px;"></div>
				<div id="buildtables" style="background-color: #fff; width:100%; height:552px;border: solid 1px #ddd; overflow: scroll;"></div>
			</div>
		</div>
		<!-- <div id="datastruct" style="background-color: #fff; border: solid 1px #ddd; width: 100%; height: 580px;margin-top:10px;display:none;overflow:auto;"></div> -->
		<div id="contextMenu1">
        	<ul>
            	<li id="addChildNode" name="addChildNode" onclick="cxcommand(this)"><a href="#" target="_self">新增子节点</a></li>
            	<li id="editCurNode" name="editCurNode" onclick="cxcommand(this)"><a href="#" target="_self">编辑节点</a></li>
          		<li id="deleteCurNode" name="deleteCurNode" onclick="cxcommand(this)"><a href="#" target="_self">删除节点</a></li>
          		<li id="deleteChildNode" name="deleteChildNode" onclick="cxcommand(this)"><a href="#" target="_self">清空节点</a></li>
          		<li id="addChildTable" name="addChildTable" onclick="cxcommand(this)"><a href="#" target="_self">选择表</a></li>
        	</ul>
		</div>
		<div id="contextMenu2">
        	<ul>
            	<li id="addChildNode" name="addChildNode" onclick="cxcommand(this)"><a href="#" target="_self">新增子节点</a></li>
            	<li id="editCurNode" name="editCurNode" onclick="cxcommand(this)"><a href="#" target="_self">编辑节点</a></li>
          		<li id="deleteCurNode" name="deleteCurNode" onclick="cxcommand(this)"><a href="#" target="_self">删除节点</a></li>
          		<li id="deleteChildNode" name="deleteChildNode" onclick="cxcommand(this)"><a href="#" target="_self">清空节点</a></li>
        	</ul>
		</div>
	</div>
</body>
</html>
